var path = require("path");
var Rx = require('rxjs');
var operators = require("rxjs/operators");
var SERVER_CONST = require("../server-const");
var express = require('express');
var router = express.Router();
var model = require("../model/chatModel");
var user = model.user;
var channels = model.channels;
var teams = model.teams;
var channelMembers = model.channelMembers;
var teamMembers = model.teamMembers;
var util = require("../server-util/util");
var mongoose = require("mongoose");
var post = model.post;

// 创建一个路由来处理根路径
router.get('/index', (req, res) => {
    // 发送 HTML 页面作为响应
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

/**
 * @api {GET} /index/search 查找成员
 * @apiSampleRequest off
 * @apiParam (params) {String} str
 * @apiGroup index
 */
router.get("/search", function (req, res, next) {
    let str = req.query.str;
    new Rx.Observable(ob => {
        user.aggregate([
            {
                $match: {
                    Username: {
                        $regex: new RegExp(str, 'ig')
                    }
                }
            },
            {
                $lookup:{
                    from: 'files',
                    localField: '_id',
                    foreignField: 'UserId',
                    as: 'files'
                }
            },
            {
                $project: {
                    Email: "$Email",
                    Username: "$Username",
                    avatar: {
                        $filter: {
                            input: "$files",
                            as: "files",
                            cond: {
                                $and: [
                                    {
                                        $eq: ["$$files.UserId", "$_id"],
                                        $eq: ["$$files.PostFileType", "avatar"]
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        ]).exec(function (err, result) {
            ob.next(result);
            ob.complete();
        })
    }).pipe(
        operators.concatMap(prev => {
            return new Rx.Observable(ob => {
                channels.aggregate([
                    {
                        $match: {
                            DisplayName: {
                                $regex: new RegExp(str)
                            }
                        }
                    }
                ]).exec(function (err, result) {
                    ob.next({
                        allMembers: prev,
                        groups: result
                    });
                    ob.complete();
                })
            })
        })
    ).subscribe(sres => {
        util.res.success({
            res,
            data: sres
        });
    })
});
module.exports = router;

